03. Threads

Threads

In this section, you'll learn what threads are and how to use them in Java.

ND079 JPND C2 L05 A03 Threads

What are Threads?

Threads are a way for programs to execute multiple tasks in parallel, at the same time.

You can think of threads as mini programs running within the program. Each thread independently executes its own Java code, which can include variables, for-loops, conditionals, method calls, etc. Anything you can run in a non-parallel Java program, you can also run in parallel, on a thread.

Threads require hardware and operating system support. In order to write programs that run multiple threads in parallel, the program must be running on a computer with a multi-thread CPU, and the operating system needs to have the required drivers.

Common Uses of Threads

  • Doing multiple tasks, such as handling multiple user requests, at the same time.

  • Perform long-running background work, such as downloading a large file. Doing this in a separate thread allows the main thread to continue doing other things while it waits for the background thread to finish.

Threads and Program Memory

When a program uses multiple threads, each thread has its own separate call stack:

The call stack is how each thread is able to execute its own code, allocate variables, and call methods independently of the other threads.

However, all threads share the same heap. This means you can have two or more threads accessing shared state, such as an ArrayList or a HashMap.

What happens if a thread tries to use more stack space than is allocated for it?

SOLUTION: The stack will overflow, an exception will be thrown, and the thread will stop running.

Creating and Running Threads

Java provides the Thread class to directly create and run threads:

Thread thread = new Thread(() -> System.out.print("world!"));
System.out.print("Hello, ");
thread.start();
thread.join();

This program prints Hello, world! to the terminal.

Virtual Threads

When you create a Thread object in Java, you're actually creating a virtual thread that's managed by the JVM. Virtual threads make it so that your program could create 10,000 Threads, even if your computer's CPU only supports 4 threads.

Virtual threads can create the illusion of having multiple threads, but your program will still not be able to achieve parallelism unless computer the program is running on supports "real" threads managed by the operating system.